package com.example.emos.workflow.bpmn;

import com.example.emos.workflow.db.dao.TbLeaveDao;
import com.example.emos.workflow.db.dao.TbUserDao;
import com.example.emos.workflow.exception.EmosException;
import com.example.emos.workflow.task.MailTask;
import com.example.emos.workflow.util.MailConst;
import org.activiti.engine.HistoryService;
import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.JavaDelegate;
import org.activiti.engine.history.HistoricTaskInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.HashMap;

@Component
public class NotifyLeaveService implements JavaDelegate {

    @Autowired
    private HistoryService historyService; // 注入Activiti的历史服务，用于访问历史任务实例信息

    @Autowired
    private TbLeaveDao leaveDao; // 注入自定义的请假记录数据访问对象

    @Autowired
    private TbUserDao userDao; // 注入自定义的用户数据访问对象

    @Autowired
    private MailTask mailTask; // 注入用于发送邮件的任务

    @Override
    public void execute(DelegateExecution delegateExecution) {
        // 查询历史任务实例，通常是找到最近一次任务执行的记录
        HistoricTaskInstance taskInstance = historyService.createHistoricTaskInstanceQuery()
                .includeProcessVariables()
                .includeTaskLocalVariables()
                .processInstanceId(delegateExecution.getProcessInstanceId())
                .orderByHistoricTaskInstanceEndTime()
                .orderByTaskCreateTime()
                .asc()
                .list()
                .get(0);

        String result = taskInstance.getTaskLocalVariables().get("result").toString(); // 获取任务的本地变量 "result"
        delegateExecution.setVariable("result", result); // 设置流程实例的变量 "result"，用于传递任务结果

        String instanceId = delegateExecution.getProcessInstanceId(); // 获取当前流程实例的ID

        // 构造更新请假记录状态的参数
        HashMap param = new HashMap() {{
            put("status", "同意".equals(result) ? 3 : 2); // 如果任务结果为 "同意"，则状态为3；否则为2
            put("instanceId", instanceId); // 请假记录的流程实例ID
        }};

        int rows = leaveDao.updateLeaveStatus(param); // 更新请假记录的状态
        if (rows != 1) {
            throw new EmosException("更新请假记录状态失败"); // 如果更新失败，抛出自定义异常
        }
        mailTask.sendMail(MailConst.MailType.LEAVE.getType(), instanceId, result); // 发送请假相关的邮件通知
        delegateExecution.setVariable("filing", true); // 设置流程实例的变量 "filing" 为 true，表示已经完成归档
    }
}
